package com.xiongmm.stream.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author XiongMM
 * @date 2019/5/27
 */
public class PropertiesUtil {

    private static Map<String, String> confs = new ConcurrentHashMap<String, String>();
    private static final String FILE_NAME = "application.properties";
    private final static Logger LOGGER = LoggerFactory.getLogger(PropertiesUtil.class);

    static {
        loadConf();
    }

    private static void loadConf() {
        Properties props = new Properties();
        InputStream in = getClassLoader().getResourceAsStream(FILE_NAME);

        try {
            props.load(in);
            for (Object key : props.keySet()) {
                Object value = props.get(key);
                confs.put((String) key, (String) value);
            }
        } catch (IOException e) {
            LOGGER.error("load config file error", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {

                }
            }
        }
    }

    private static ClassLoader getClassLoader() {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader == null) {
            classLoader = PropertiesUtil.class.getClassLoader();
        }
        return classLoader;
    }

    public static String getValue(String key) {
        return confs.get(key);
    }
}
